<?php
/**
 *
 * @authors Liujinbi (857053791@QQ.com)
 * @date    2017-08-08 14:55:37
 * @version $Id$
 */
namespace app\mall\controller;

use think\Config;
use think\Db;
use think\Session;
use think\Controller;
use Payinterface\PaySdk;

class Order extends Base
{
    public $error = [];
    //用户订单列表
    function index()
    {
        $uid = $this->uid;
        $params = Request()->param();
        $query = Db::table('sdzx_order')->alias('o')
        ->join('sdzx_order_goods g', 'o.order_id=g.order_id')
        ->where("o.order_status > -1 and o.user_id={$uid}")
        ->order('o.create_time desc');
        if (isset($params['status'])) {
            switch ($params['status']) {
                case 'all':
                    # 所有订单
                    break;
                case '1':
                    # 待支付
                    $query->where("o.order_status=0 or o.order_status=25");
                    break;
                case '2':
                    # 待发货
                    $query->where("o.order_status=30 or o.order_status=20");
                    break;
                case '3':
                    # 待收货
                    $query->where("o.order_status=40");
                    break;
                case '4':
                    # 待评价
                    $query->where("o.order_status=100 and o.is_evaluate=0");
                    break;
                default:
                    # 默认只查出未完成的订单
                    // $query->where("o.order_status >= 0 and o.order_status < 100");
                    break;
            }
        }

        $page = isset($params['page'])?$params['page']:1;
        $list = $query->select();
        // 订单合并
        $tmp_arr=[];
        foreach ($list as $k => $v) {
            if (!isset($tmp_arr[$v['order_id']])) {
                $order = [
                    'order_id'          => $v['order_id'],
                    'order_no'          => $v['order_no'],
                    'order_type'        => $v['order_type'],  //订单类型1：自主下单 2：代下单
                    'payment_type'      => $v['payment_type'], //支付类型  1：自主支付 2：管家支付
                    'user_id'           => $v['user_id'],
                    'user_name'         => $v['user_name'],
                    'agent_id'          => $v['agent_id'], //管家ID订单类型为 代下单 是才有
                    'agent_name'        => $v['agent_name'],
                    'create_time'       => $v['create_time'],
                    'receiver_name'     => $v['receiver_name'],
                    'receiver_mobile'   => $v['receiver_mobile'],
                    // 'receiver_province' => $v['receiver_province'],
                    // 'receiver_city'     => $v['receiver_city'],
                    // 'receiver_district' => $v['receiver_district'],
                    'receiver_address'  => $v['receiver_address'],
                    'receiver_pcd'      => $v['receiver_pcd'],
                    'goods_money'       => $v['goods_money'],
                    'order_money'       => $v['order_money'],
                    'coupon_money'      => $v['coupon_money'],
                    'coupon_id'         => $v['coupon_id'],
                    'user_money'        => $v['user_money'],
                    'shipping_money'    => $v['shipping_money'],
                    'order_status'      => $v['order_status'],
                    'pay_platform'      => $v['pay_platform'],
                    'refund_money'      => $v['refund_money'],
                    'refund_time'       => date('Y-m-d',strtotime($v['refund_time']))
                ];
                $tmp_arr[$v['order_id']] = $order;
            }
            $tmp_arr[$v['order_id']]['list'][] = $v;
        }
        //分类统计
        $statusNum=['all'=>0];
        $return_arr=[];
        foreach ($tmp_arr as $k => $v) {
            if (isset($statusNum[$v['order_status']])) {
                $statusNum[$v['order_status']]++;
            } else {
                $statusNum[$v['order_status']]=1;
            }
            $statusNum['all']++;
            $return_arr[] = $v;
        }
        $this->success('success', '', ['list'=>$return_arr,'statusNum'=>$statusNum]);
    }

    /**
     * 判断今天配送还是明天配送
     * @return [type] [description]
     */
    function scheduling()
    {
        if (isset($data['scheduling']) && $data['scheduling']==1) { //用户指定明天送
            $this->error('您选择了次日配送（'.date('Y-m-d', strtotime('+1 day')).'）');
        } elseif (Config::get('sites.scheduling')) {
            $scheduling_time = strtotime(Config::get('sites.scheduling'));
            if (time()<=$scheduling_time) {
                $this->success('今天');
            } else {
                $this->error(Config::get('sites.scheduling').' 后下单将为您次日配送（'.date('Y-m-d', strtotime('+1 day')).'）');
            }
        } else {
            $this->success('今天');
        }
    }
    /**
     * 下单
     */
    function add()
    {
        //{specval_id:23_2,25_2,28_2,address_id:14}
        $data = Request()->param();
        !isset($data['specval_id']) && $this->error('未选择商品');
        !isset($data['address_id']) && $this->error('未选择收获地址');
        $data['specval_id'] = explode(',', $data['specval_id']);

        //通过规格ID 查出商品
        $goods = [];
        foreach ($data['specval_id'] as $k => $v) {
            $id_num = explode('_', $v);
            if ($id_num[1]<=0) {
                continue;
            }
            $tmp = Db::connect([], 'goods')->field('g.*,sval.*,s.supplier_id,s.supplier_name,b.brand_id,b.brand_name')
            ->table('sdzx_goods')->alias('g')
            ->join('sdzx_goods_specval sval', 'g.goods_id=sval.goods_id')
            ->join('sdzx_goods_brand b', 'g.brand_id=b.brand_id', 'left')
            ->join('sdzx_supplier s', 'sval.supplier_id=s.supplier_id', 'left')
            ->where("sval.specval_id={$id_num[0]}")
            ->find();
            $tmp['num'] = $id_num[1];
            $goods[] = $tmp;
        }
        if (empty($goods)) {
            $this->error('未选择商品');
        }

        $order_money = 0; //订单总价
        //查商品活动价格
        # ToDo
        
        //金券支付金额
        # ToDo
        $coupon_id=0;
        $coupon_money=0;
        if (isset($data['coupon_id'])) {
            # code...
        }

        //计算商品价格
        $goods_money=0;
        $total_cost_price=0;
        foreach ($goods as $k => $v) {
            $goods_money += $v['price']*$v['num'];
            $total_cost_price += $v['cost_price']*$v['num'];
        }
        $order_money += $goods_money;

        //订单运费
        $shipping_money = $this->shippingMoney($order_money);
        $order_money += $shipping_money['delivery_fee'];
        

         //如果用户使用余额使用
         $user_money=0;
        if (isset($data['user_money'])) {
            # code...
        }
        
        

        //收货地址
        $address = Db::name('user_address')->where(['address_id'=>$data['address_id'],'user_id'=>$this->uid])->find();
        !$address && $this->error('收获地址错误');

        $time = date('Y-m-d H:i:s');
        $order = [
            'order_no'          => $this->orderSn(),
            'order_type'        => 1,  //订单类型1：自主下单 2：代下单
            'payment_type'      => 1, //支付类型  1：自主支付 2：管家支付
            'user_id'           => $this->uid,
            'user_name'         => $this->user['realname'],
            'openid'            => $this->user['openid'],
            'agent_id'          => '', //管家ID订单类型为 代下单 是才有
            'agent_name'        => '',
            'create_time'       => $time,
            'receiver_name'     => $address['name'], //收货人姓名
            'receiver_mobile'   => $address['phone'],
            // 'receiver_province' => $address['province'],
            // 'receiver_city'     => $address['city'],
            // 'receiver_district' => $address['district'],
            'receiver_address'  => $address['address'],
            'receiver_pcd'      => $address['pcd'],
            'goods_money'       => $goods_money, //商品总价
            'order_money'       => $order_money, //订单总价
            'coupon_money'      => $coupon_money, //订单代金券支付金额
            'coupon_id'         => $coupon_id,
            'user_money'        => $user_money, //订单余额支付金额
            'shipping_money'    => $shipping_money['delivery_fee'], //订单运费
            'order_status'      => 0,
            'remarks'           => $data['remarks']?:''
            // 'pay_platform'      => '',
        ];

        //配送时间
        if (isset($data['scheduling']) && $data['scheduling']==1) { //用户指定明天送
            $order['scheduling'] = date('Y-m-d', strtotime('+1 day'));
        } elseif (Config::get('sites.scheduling')) {
            $scheduling_time = strtotime(Config::get('sites.scheduling'));
            if (time()<=$scheduling_time) {
                $order['scheduling'] = date('Y-m-d');
            } else {
                $order['scheduling'] = date('Y-m-d', strtotime('+1 day'));
            }
        } else {
            $order['scheduling'] = date('Y-m-d');
        }

        Db::startTrans();
        $order_id = Db::name('order')->insertGetId($order);

        if (!$order_id) {
            Db::rollback();
            $this->error('订单保存失败');
        }
        $order_goods=[];
        foreach ($goods as $key => $value) {
            $order_goods[] = [
                'order_id'           => $order_id,
                'goods_name'         => $value['goods_name'],
                'goods_id'           => $value['goods_id'],
                'goods_spec_id'      => $value['spec_id'],
                'goods_spec_name'    => $value['spec_name'],
                'goods_specval_id'   => $value['specval_id'],
                'goods_specval_name' => $value['specval_name'],
                'supplier_name'      => $value['supplier_name'],
                'supplier_id'        => $value['supplier_id'],
                'price'              => $value['price'],
                'cost_price'         => $value['cost_price'],
                'num'                => $value['num'],
                'goods_picture'      => $value['picture'],
                'brand_id'           => $value['brand_id'],
                'brand_name'         => $value['brand_name'],
            ];
        }
        $re_order_goods = Db::name('order_goods')->insertAll($order_goods);
        if (!$re_order_goods) {
            Db::rollback();
            $this->error('订单保存失败');
        }

        //查看订单号是否存在  存在则是错的
        $isset = Db::name('order_prepay')->where(['order_no'=>$order['order_no'],'prepay_type'=>0])->find();
        $isset && $this->error('下单失败，请重新提交订单');

        //支付中间表 避免订单号重复
        $prepay_date['out_trade_no'] = $order_id.time();
        $order['out_trade_no'] = $prepay_date['out_trade_no'];

        // 生成支付参数
        $order['order_id']   = $order_id;
        $order['time_start'] = $time;
        $order['body']       = Config::get('site.title');
        // $order['detail']     = '';

        $parameters = $this->wxPay($order);
        if ($parameters['status']) {
            $parameters['data']['pay_info'] = json_decode($parameters['data']['pay_info'],true);
            $prepay_id = $parameters['data']['pay_info']['package'];
            $prepay_id = ltrim($prepay_id,'prepay_id=');
            // 清除购物车数据
            Db::name('user_cart')->where(['specval_id'=>['in',$data['specval_id']],'user_id'=>$this->uid,['addbyagent']=>0])->delete();

            $prepay_date['parameters']   = json_encode($parameters['data']);
            
            $parameters['order_id'] = $order_id;
   
            $prepay_date['order_no']     = $order['order_no'];
            $prepay_date['order_id']     = $order['order_id'];
            $prepay_date['out_trade_no'] = $order['out_trade_no'];
            $prepay_date['body']         = $order['body'];
            // $prepay_date['detail']       = $order['detail'];
            $prepay_date['total_fee']    = $order['order_money']*100;
            $prepay_date['time_start']   = $order['time_start'];
            $prepay_date['trade_type']   = 'JSAPI';
            $prepay_date['prepay_id']    = $prepay_id;
            $prepay_date['prepay_type']  = 0;
            $prepay_date['payment_type'] = 1;
            
            if (isset($order['time_expire'])) {
                $prepay_date['time_expire'] = $order['time_expire'];
            }
            if (isset($order['goods_tag'])) {
                $prepay_date['goods_tag'] = $order['goods_tag'];
            }

            Db::name('order_prepay')->insert($prepay_date);

            Db::name('order_action')->insert([
                'user_id'          => $this->uid,
                'order_id'         => $order_id,
                'act_time'         => $time,
                'order_status'     => 0,
                'bop_order_status' => 0
            ]);

            Db::commit();
            $re_arr['parameters'] = $parameters['data']['pay_info'];
            $re_arr['parameters']['order_id'] = $order_id;

            $this->success('下单成功', '', $re_arr);
        } else {
            Db::rollback();
            $this->error('支付错误', '', $parameters['msg']);
        }
    }

    /**
     * 生成订单号
     * @return [type] [description]
     */
    function orderSn()
    {
        $u = strrev(sprintf('%04s', substr($this->uid, -4)));
        $sn = $u.date('ymdHi').sprintf('%02s', rand(0, 99));
        return $sn;
    }

    /**
     * 删除订单
     * @return [type] [description]
     */
    function del()
    {
        $data = Request()->param();
        !$data['ids'] && $this->error('参数错误');
        $re = Db::name('order')->where(['user_id'=>$this->uid,'order_id'=>['in',$data['ids']]])->updata(['order_status'=>-1]);
        if ($re!==false) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

    /**
     * 历史订单支付
     * @return [type] [description]
     */
    function rePay()
    {
        $orderID = Request()->param('order_id');
        !$orderID && $this->error('参数错误');
        $time = date('Y-m-d H:i:s');
        $order = Db::name('order')->where(['order_id'=>$orderID])->find();

        $time_expire = date('Y-m-d H:i:s', strtotime('-1 hours'));

        if ($order['order_status']==25) { //补差价
            $change_price = Db::name('order_change')->where(['order_id'=>$orderID])->order('change_id desc')->find();
            //先看之前的prepay_id 有没有过期(有效期 2 小时)
            $prepay = Db::name('order_prepay')->where(['order_id'=>$order['order_id'],'prepay_type'=>1,'status'=>0])->find();
            $usefull = false;
            if ($prepay['time_start'] > $time_expire) {
                $usefull = true;
            }

            if ($prepay['payment_type'] != 1) {
                $usefull = false;
            }

            if (empty($prepay['parameters'])) {
                $usefull = false;
            }

            if ($prepay['time_expire'] !=0 && $time > $prepay['time_expire']) {
                $usefull = false;
            }

            if ($prepay['total_fee'] != 100*$change_price['price']) {
                $usefull = false;
            }

            if ($usefull) {
                $re_arr = json_decode($prepay['parameters'],true);
                $this->success('下单成功1', '', ['parameters'=>$re_arr['pay_info']]);
            } else {
                //支付中间表 避免订单号重复
                $prepay_date['out_trade_no']  = $order['order_id'].time();
                $change_order['out_trade_no'] = $prepay_date['out_trade_no'];
                $change_order['order_no']     = $order['order_no'];
                $change_order['order_id']     = $order['order_id'];
                $change_order['time_start']   = $time;
                $change_order['body']         = Config::get('site.title').'订单补价';
                // $change_order['detail']       = '';
                $change_order['order_money']  = $change_price['price'];

                $parameters = $this->wxPay($change_order);
                if ($parameters['status']) {
                    $parameters['data']['pay_info'] = json_decode($parameters['data']['pay_info'],true);
                    $prepay_id = $parameters['data']['pay_info']['package'];
                    $prepay_id = ltrim($prepay_id,'prepay_id=');

                    $prepay_date['parameters']   = $parameters['data'];

                    $prepay_date['order_no']     = $change_order['order_no'];
                    $prepay_date['order_id']     = $change_order['order_id'];
                    $prepay_date['body']         = $change_order['body'];
                    // $prepay_date['detail']       = $change_order['detail'];
                    $prepay_date['total_fee']    = $change_order['order_money']*100;
                    $prepay_date['time_start']   = $time;
                    $prepay_date['trade_type']   = 'JSAPI';
                    $prepay_date['prepay_id']    = $prepay_id;
                    $prepay_date['prepay_type']  = 1;
                    $prepay_date['payment_type'] = 1;

                    // 查看是否存在 prepay
                    $isset = Db::name('order_prepay')->where(['order_id'=>$change_order['order_id'],'prepay_type'=>1,'status'=>0])->find();
                    if ($isset) {
                        Db::name('order_prepay')->where(['order_id'=>$order['order_id'],'prepay_type'=>1,'status'=>0])->update($prepay_date);
                    } else {
                        Db::name('order_prepay')->insert($prepay_date);
                    }

                    $re_arr = $parameters['data']['pay_info'];
                    $re_arr['order_id'] = $orderID;
                    $this->success('下单成功2', '', ['parameters'=>$re_arr]);
                }
            }
            $this->error('支付错误', '');
        }

        //先看之前的prepay_id 有没有过期(有效期 2 小时)
        $prepay = Db::name('order_prepay')->where(['order_id'=>$order['order_id'],'prepay_type'=>0])->find();
        $usefull = false;
        if ($prepay['time_start'] > $time_expire) {
            $usefull = true;
        }

        if ($prepay['payment_type'] != 1) {
                $usefull = false;
            }

        if (empty($prepay['parameters'])) {
            $usefull = false;
        }

        if ($prepay['time_expire'] !=0 && $time > $prepay['time_expire']) {
            $usefull = false;
        }

        if ($prepay['total_fee'] != $order['order_money']*100) {
            $usefull = false;
        }

        if ($usefull) {
            $re_arr = json_decode($prepay['parameters'],true);
            $this->success('下单成功3', '', ['parameters'=>$re_arr['pay_info']]);
        } else {
            //支付中间表 避免订单号重复
            $prepay_date['out_trade_no'] = $order['order_id'].time();
            $order['out_trade_no'] = $prepay_date['out_trade_no'];

            // 生成支付参数
            $order['time_start'] = $time;
            $order['body']       = Config::get('site.title');
            // $order['detail']     = '';

            $parameters = $this->wxPay($order);
            if ($parameters['status']) {
                $parameters['data']['pay_info'] = json_decode($parameters['data']['pay_info'],true);
                $prepay_id = $parameters['data']['pay_info']['package'];
                $prepay_id = ltrim($prepay_id,'prepay_id=');
                $prepay_date['parameters']   = json_encode($parameters['data']);
                
                $prepay_date['order_no']     = $order['order_no'];
                $prepay_date['order_id']     = $order['order_id'];
                $prepay_date['out_trade_no'] = $order['out_trade_no'];
                $prepay_date['body']         = $order['body'];
                // $prepay_date['detail']       = $order['detail'];
                $prepay_date['total_fee']    = $order['order_money']*100;
                $prepay_date['time_start']   = $order['time_start'];
                $prepay_date['trade_type']   = 'JSAPI';
                $prepay_date['prepay_id']    = $prepay_id;
                $prepay_date['prepay_type']  = 0;
                $prepay_date['payment_type'] = 1;

                if (isset($order['time_expire'])) {
                    $prepay_date['time_expire'] = $order['time_expire'];
                }
                if (isset($order['goods_tag'])) {
                    $prepay_date['goods_tag'] = $order['goods_tag'];
                }

                // 查看是否存在 prepay
                $isset = Db::name('order_prepay')->where(['order_id'=>$order['order_id'],'prepay_type'=>0])->find();
                if ($isset) {
                    Db::name('order_prepay')->where(['order_id'=>$order['order_id'],'prepay_type'=>0])->update($prepay_date);
                } else {
                    Db::name('order_prepay')->insert($prepay_date);
                }

                $re_arr = $parameters['data']['pay_info'];
                $re_arr['order_id'] = $order['order_id'];
                $this->success('下单成功4', '', ['parameters'=>$re_arr]);
            } else {
                $this->error('支付错误', '', $this->error);
            }
        }
    }

    /**
     * 微信支付
     * @param  [type] $order [description]
     * @return [type]        [description]
     */
    function wxPay($order)
    {

        $cfg = Config::get('pay.wx');
        $PaySdk = new PaySdk($cfg);

        $cfg_xcx = Config::get('wx.xcx');

        $arr = array(
            'out_trade_no'  => $order['out_trade_no'],
            'sub_openid'    => $this->user['openid'],
            'body'          => $order['body'],
            'total_fee'     => $order['order_money']*100,
            'mch_create_ip' => gethostbyname($_SERVER["SERVER_NAME"]),
            'is_minipg'     => 1,
            'sub_appid'     => $cfg_xcx['appid']
        );
        
        $re = $PaySdk->submitOrderInfo($arr);
        return $re;


        // $config = Config::get('wx');
        // $con = array_merge($config['pay'], $config['xcx']);
        // $con['notify_url'] = request()->domain().$con['notify_url'];
        // $WxpaySdk = new WxpaySdk($con);

        // if ($history) {
        //     // $pay_order = $order;
        //     return $order['parameters'];
        // } else {
        //     $param = [
        //         'body'         => $order['body'],
        //         'out_trade_no' => $order['out_trade_no'],
        //         'openid'       => $this->user['openid'],
        //         'detail'       => $order['detail'],
        //         'total_fee'    => $order['order_money']*100,
        //         'time_start'   => $order['time_start']
        //     ];
        //     if (isset($order['time_expire'])) {
        //         $param['time_expire'] = $order['time_expire'];
        //     }
        //     $pay_order = $WxpaySdk->xcxPay($param);
        // }
        // if ($pay_order['return_code'] == 'SUCCESS' && $pay_order['result_code'] == 'SUCCESS') {
        //     $parameters = $WxpaySdk->GetJsApiParameters($pay_order);
        //     return $parameters;
        // } else {
        //     $this->error = $pay_order;
        //     return false;
        // }
    }

    /**
     * 支付成功后需要访问该接口确定订单的支付状态
     * @return [type] [description]
     */
    function payOk()
    {
        $orderID = Request()->param('order_id');
        !$orderID && $this->error('参数错误');

        //查看订单支付状态
        $order = Db::connect([], 'order')->name('order')->where(['order_id'=>$orderID])->find();
        if ($order['pay_status']) {
            $this->addFreqlist($orderID);
            $this->success('success');
        } else {
            $cfg = Config::get('pay.wx');
            $PaySdk = new PaySdk($cfg);

            $pay = $PaySdk->queryOrder(array('transaction_id'=>$order['pay_no']));
            if ($pay['status']) {
                $this->addFreqlist($orderID);
                $this->success('支付成功');
            }else{
                $this->error('支付失败', '');
            }

            //调用微信接口 查看支付状态
            // $config = Config::get('wx');
            // $con = array_merge($config['pay'], $config['xcx']);
            // $con['notify_url'] = request()->domain().$con['notify_url'];
            // $WxpaySdk = new WxpaySdk($con);
            // $resoult = $WxpaySdk->orderQuery($order);
            // if ($resoult['trade_state'] == 'SUCCESS') {
            //     $this->addFreqlist($orderID);
            //     // 这里不修改订单状态了，统一在支付回调中修改 并且发模板消息
            //     $this->success('支付成功');
            //     // if ($order['pay_status'] == 1) {
            //     //     $this->success('支付成功','',$order);
            //     // }
            //     // # 支付成功
            //     // $update = [
            //     //     'pay_no'       => $resoult['transaction_id'],
            //     //     'pay_time'     => date('Y-m-d H:i:s'),
            //     //     'pay_money'    => $resoult['total_fee']/100, //转换为元
            //     //     'pay_status'   => 1
            //     // ];

            //     // if ($order['order_status'] == 0) {
            //     //     $update['order_status'] = 20;
            //     // }
            //     // Db::connect([],'order')->name('order')->where(['order_id'=>$orderID])->update($update);
            //     // $order = Db::connect([],'order')->name('order')->where(['order_id'=>$orderID])->find();
            //     // $this->success('支付成功','',$order);
            // } else {
            //     $this->error('支付失败', '');
            // }
        }
    }

    public function addFreqlist($orderID)
    {
        $goods = Db::field('o.user_id,og.goods_id')
        ->table('sdzx_order_goods')->alias('og')
        ->join('sdzx_order o','og.order_id=o.order_id')
        ->group('og.goods_id')
        ->where("o.order_id={$orderID}")->select();

        if ($goods) {
            $insD = [];$time = date('Y-m-d H:i:s');
            foreach ($goods as $k => $v) {
                if ( Db::name('user_freqlist')->where(['goods_id'=>$v['goods_id']])->find() ) {
                    continue;
                }
                $insD[] = [
                    'user_id'  => $v['user_id'],
                    'goods_id' => $v['goods_id'],
                    'add_time' => $time,
                ];
            }
            Db::name('user_freqlist')->insertAll($insD);
        }
    }


    public function closeWxorder($order)
    {
        $config = Config::get('wx');
        $con = array_merge($config['pay'], $config['xcx']);
        $con['notify_url'] = request()->domain().$con['notify_url'];
        $WxpaySdk = new WxpaySdk($con);
        $resoult = $WxpaySdk->closeOrder($order);
        return $resoult;
    }

    /**
     * 取消订单
     * @return [type] [description]
     */
    function cancel()
    {
        $data = Request()->param();
        !isset($data['order_id']) && $this->error('未选择订单');

        $order = Db::name('order')->where(['order_id'=>$data['order_id'],'user_id'=>$this->uid])->find();
        !$order  && $this->error('订单不存在');

        if ($order['pay_status']) {
            $this->error('订单已支付');
        }

        $re = Db::name('order')->where(['order_id'=>$data['order_id'],'user_id'=>$this->uid])->update(['order_status'=>-1]);

        if ($re!==false) {
            Db::name('order_action')->insert([
                'user_id'          => $this->uid,
                'order_id'         => $data['order_id'],
                'act_time'         => date('Y-m-d H:i:s'),
                'order_status'     => -1,
                'bop_order_status' => $order['order_status']
            ]);
            $this->success('取消成功');
        } else {
            $this->error('取消失败');
        }
    }

    /**
     * 取消订单需要审核
     * @return [type] [description]
     */
    function excancel()
    {
        $data = Request()->param();
        !isset($data['order_id']) && $this->error('未选择订单');

        $order = Db::name('order')->where(['order_id'=>$data['order_id'],'user_id'=>$this->uid])->find();
        !$order  && $this->error('订单不存在');

        $re = Db::name('order')->where(['order_id'=>$data['order_id'],'user_id'=>$this->uid])->update(['order_status'=>5]);

        if ($re!==false) {
            Db::name('order_action')->insert([
                'user_id'          => $this->uid,
                'order_id'         => $data['order_id'],
                'act_time'         => date('Y-m-d H:i:s'),
                'order_status'     => 5,
                'bop_order_status' => $order['order_status']
            ]);
            $this->success('取消成功');
        } else {
            $this->error('取消失败');
        }
    }

    /**
     * 订单的操作记录
     * @return [type] [description]
     */
    function orderAct()
    {
        $data = Request()->param();
        !isset($data['order_id']) && $this->error('未选择订单');
        $order = Db::name('order')->where(['order_id'=>$data['order_id']])->find();
        $order['scheduling'] = date('Y-m-d', strtotime($order['scheduling']));

        $list = Db::name('order_action')->where(['order_id'=>$data['order_id'],'user_id'=>$this->uid])->order('act_time asc')->select();
        foreach ($list as $k => $v) {
            $_remark = null;
            if ($v['act_remark']) {
                $remark_arr = explode('||',$v['act_remark']);
                $_remark = rtrim(array_shift($remark_arr),'||');
                if ($remark_arr) {
                    $v['msg_list'] = array_filter($remark_arr);
                }
            }
            
            switch ($v['order_status']) {
                case -1:
                    $v['msg'] =  $_remark?:'您的订单已取消';
                    break;
                case 0:
                    $v['msg'] = $_remark?:'您的订单已提交等待支付';
                    break;
                case 5:
                    $v['msg'] = $_remark?:'您的取消订单申请已提交，请等待审核';
                    break;
                case 10:
                    $v['msg'] = $_remark?:'您的订单已取消';
                    break;
                case 20:
                    $v['msg'] = $_remark?:'您的订单已支付成功，请等待系统确认';
                    break;
                case 24:
                    $v['msg'] = $_remark?:'您的订单金额已发生变化';
                    break;
                case 25:
                    $v['msg'] = $_remark?:'您的订单金额已发生变化';
                    break;
                case 30:
                    $v['msg'] = $_remark?:'您的订单已被确认，正在备货中';
                    break;
                case 40:
                    $v['msg'] = $_remark?:'您的订单备货完成，正在发货中';
                    break;
                case 50:
                    $v['msg'] = $_remark?:'您的订单退货中';
                    break;
                case 100:
                    $v['msg'] = $_remark?:'您的订单已完成';
                    break;
                default:
                    $v['msg'] = $_remark?:'您的订单已删除';
                    break;
            }
            if ((sizeof($list)-1)==$k) {
                $v['is_last'] = true;
            }
            $list[$k] = $v;
        }
        $data['list'] = $list;
        $data['order'] = $order;
        $this->success('success', '', $data);
    }

    /**
     * 通过规格ID获取商品
     * @return [type] [description]
     */
    function getGoods()
    {
         //{specval_id:[21_2,21_2],address_id:1}
        $data = Request()->param();
        !isset($data['specval_id']) && $this->error('未选择商品');

        //通过规格ID 查出商品
        $goods = Db::connect([], 'goods')->field('g.*,sval.*,s.supplier_id,s.supplier_name')
        ->table('sdzx_goods')->alias('g')
        ->join('sdzx_goods_specval sval', 'g.goods_id=sval.goods_id')
        ->join('sdzx_supplier s', 'sval.supplier_id=s.supplier_id', 'left')
        ->where(['specval_id'=>['in',$data['specval_id']]])
        ->select();

        $this->success('success', '', $goods);
    }

    /**
     * 订单详情
     * @param string $value [description]
     */
    function orderDetail()
    {
        $data = Request()->param();
        !isset($data['order_id']) && $this->error('未选择订单');

        $list = Db::table('sdzx_order')->alias('o')
        ->join('sdzx_order_goods g', 'o.order_id=g.order_id')
        ->where("o.order_id={$data['order_id']}")
        ->select();

        // 订单合并
        $tmp_arr=[];
        foreach ($list as $k => $v) {
            if (!isset($tmp_arr['order_no'])) {
                $tmp_arr = [
                    'order_no'          => $v['order_no'],
                    'order_id'          => $v['order_id'],
                    'order_type'        => $v['order_type'],  //订单类型1：自主下单 2：代下单
                    'payment_type'      => $v['payment_type'], //支付类型  1：自主支付 2：管家支付
                    'user_id'           => $v['user_id'],
                    'user_name'         => $v['user_name'],
                    'agent_id'          => $v['agent_id'], //管家ID订单类型为 代下单 是才有
                    'agent_name'        => $v['agent_name'],
                    'create_time'       => $v['create_time'],
                    'receiver_name'     => $v['receiver_name'],
                    'receiver_mobile'   => $v['receiver_mobile'],
                    // 'receiver_province' => $v['receiver_province'],
                    // 'receiver_city'     => $v['receiver_city'],
                    // 'receiver_district' => $v['receiver_district'],
                    'receiver_address'  => $v['receiver_address'],
                    'receiver_pcd'      => $v['receiver_pcd'],
                    'goods_money'       => $v['goods_money'],
                    'order_money'       => $v['order_money'],
                    'coupon_money'      => $v['coupon_money'],
                    'coupon_id'         => $v['coupon_id'],
                    'user_money'        => $v['user_money'],
                    'shipping_money'    => $v['shipping_money'],
                    'order_status'      => $v['order_status'],
                    'pay_platform'      => $v['pay_platform'],
                    'refund_money'      => $v['refund_money'],
                    'refund_time'       => date('Y-m-d',strtotime($v['refund_time'])),
                    'remarks'           => $v['remarks'],
                ];
            }
            $tmp_arr['list'][] = $v;
        }
        $this->success('success', '', $tmp_arr);
    }

    /**
    * 获取用户订单运费  之后可能跟用户等级有关
    * @return [type] [description]
    */
    public function shippingMoney($order_money = 0)
    {
        $uid = $this->uid;
        $free_shipping = Db::field('ul.free_shipping')
        ->table('sdzx_shop')->alias('s')
        ->join('sdzx_user_level ul','s.level=ul.level_id','left')
        ->where("s.user_id={$uid}")
        ->value('free_shipping');

        $return_arr = [
            'delivery_fee' => Config::get('sites.delivery_fee')?:0,
            'free_delivery_fee' => Config::get('sites.free_delivery_fee')?:0
        ];

        if ($free_shipping) {
            $return_arr['delivery_fee'] = 0;
        }else if ($order_money>0 && $return_arr['free_delivery_fee']>0 && $order_money>=$return_arr['free_delivery_fee']) {
            $return_arr['delivery_fee'] = 0;
        }
        
        return $return_arr;
    }

    /**
     * 订单提交页面相关数据
     * @return [type] [description]
     */
    public function orderOther()
    {
        $data['delivery_fee'] = $this->shippingMoney();
        if (Config::get('sites.scheduling')) {
            $data['shippingmsg'] = Config::get('sites.scheduling').'前下单当日配送，'.Config::get('sites.scheduling').'后下单将次日配送';
        } else {
            $data['shippingmsg'] = "预计配送时间".date('m月d日').' 7:00-11:00';
        }
        $this->success('success', '', $data);
    }

    /**
     * 订单完成操作
     */
    public function finish()
    {
        $order_id = request()->param('order_id');
        !$order_id && $this->error('参数错误');

        $order = Db::name('order')->where(['order_id'=>$order_id])->find();
        !$order && $this->error('订单不存在');
        if ($order['order_status']==50) {
            $this->error('订单退货中');
        } else {
            $re = Db::name('order')->where(['order_id'=>$order_id])->update(['order_status'=>100]);
            if ($re!==false) {
                Db::name('order_action')->insert([
                    'user_id'          => $this->uid,
                    'order_id'         => $order_id,
                    'act_time'         => date('Y-m-d H:i:s'),
                    'order_status'     => 100,
                    'bop_order_status' => $order['order_status']
                ]);
                $this->success('success', '');
            } else {
                $this->error('操作失败', '');
            }
        }
    }

    public function neworder()
    {
        $num = Db::field('count(order_id) as num')->name('order')->where(['user_id'=>$this->uid,'order_status'=>['in',[0,25]]])->value('count(order_id)');
        $this->success('','',['num'=>$num]);
    }
}
